﻿namespace ColorWheel.Win.GradientColor.Demo
{
    using System.ComponentModel;
    using System.Windows;
    using ColorWheel.Core;
    using System.Windows.Media;

    public partial class MainWindow: 
        Window, 
        INotifyPropertyChanged
    {
        public Palette                                  m_palette;
        public event PropertyChangedEventHandler        PropertyChanged;

        private ColorManager                            m_cm;

        public MainWindow()
        {
            InitializeComponent();

            m_cm = (new ColorManager()).Global;

            Palette = Palette.Create(new RGBColorWheel(), Colors.White, PaletteSchemaType.Custom, ColorManager.Templates.Count);

            int i = 0;
            foreach (var kv in ColorManager.Templates)
            {
                if (kv.Value.Color != null)
                {
                    Palette.Colors[i].Name = kv.Value.Title;
                    Palette.Colors[i].Tag = kv.Value;
                    Palette.Colors[i].RgbColor = kv.Value.Color.Value;
                    Palette.Colors[i].PropertyChanged += OnColorChanged;
                    ++i;
                }
            }

            colorTree.ItemsSource = m_cm.GetColorTree(true);
            DataContext = this;
        }

        void OnColorChanged(
            object                                      sender, 
            PropertyChangedEventArgs                    e
        )
        {
            PaletteColor                                pc;
            TemplateColor                               tc;

            if (e.PropertyName == "Color")
            {
                pc = sender as PaletteColor;
                tc = ColorManager.GetTemplate(((TemplateColor) pc.Tag).Name);

                tc.Color = pc.RgbColor;
                ColorManager.Instance.ClearCache();
            }
        }

        private void Window_Loaded(
            object                                      sender, 
            RoutedEventArgs                             e
        )
        {
        }

        private void FirePropertyChanged(
            string                                      name
        )
        {
            if(PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }

        public Palette Palette
        {
            get
            {
                return m_palette;
            }
            set
            {
                m_palette = value;
                FirePropertyChanged("Palette");
            }
        }
    }
}
